<template>
	<view class="app">
		<!-- <view class="price-box">
			<text>支付金额</text>

			<text class="price">{{orderInfo.payAmount}}</text>
		</view> -->
		
		<!-- 倒计时显示 -->
		<view class="countdown-box" v-if="countdownTime > 0">
			<view class="countdown-title">订单将在以下时间后自动取消</view>
			<view class="countdown-time">{{formatCountdown}}</view>
		</view>
		
		<!-- 商品信息显示 -->
		<view class="goods-section" v-if="orderInfo.productList && orderInfo.productList.length > 0">
			<view class="g-header b-b">
				<image class="logo" :src="orderInfo.shopInfo.logo"></image>
				<text class="name">{{orderInfo.shopInfo.name}}</text>
			</view>
			<!-- 商品列表 -->
			<view class="g-item" v-for="(item, index) in orderInfo.productList" :key="index">
				<image :src="item.image"></image>
				<view class="right">
					<text class="title clamp">{{item.title}}</text>
					<text class="spec">{{item.spec}}</text>
					<view class="price-box">
						<text class="price">￥{{item.price}}</text>
						<text class="number">x {{item.quantity}}</text>
					</view>
				</view>
			</view>
		</view>

		<view class="pay-type-list">

			<view class="type-item b-b" @click="changePayType(1)">
				<text class="icon yticon icon-weixinzhifu"></text>
				<view class="con">
					<text class="tit">微信支付</text>
					<text>推荐使用微信支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == 1' />
				</label>
			</view>
			<view class="type-item b-b" @click="changePayType(2)">
				<text class="icon yticon icon-alipay"></text>
				<view class="con">
					<text class="tit">支付宝支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == 2' />
				</label>
			</view>
			<view class="type-item" @click="changePayType(3)">
				<text class="icon yticon icon-erjiye-yucunkuan"></text>
				<view class="con">
					<text class="tit">预存款支付</text>
					<text>可用余额 ¥198.5</text>
				</view>
				<label class="radio">
					<radio value="" color="#fa436a" :checked='payType == 3' />
				</label>
			</view>
		</view>
		
		<text class="mix-btn" @click="confirm">确认支付</text>
	</view>
</template>

<script>
	import api from '@/utils/api'
	
	export default {
		data() {
			return {

				payType: 1, // 1:微信, 2:支付宝, 3:钱包支付
				orderInfo: {
					orderId: '',
					payAmount: 0,
					productList: [],
					shopInfo: {},
					createTime: null // 订单创建时间
				},
				countdownTime: 0, // 倒计时剩余秒数
				countdownTimer: null, // 倒计时定时器
				checkOrderStatusTimer: null, // 检查订单状态定时器
				timeoutHours: 24 // 超时时间（小时），可配置
			};
		},
		computed: {
			// 格式化倒计时显示
			formatCountdown() {
				if (this.countdownTime <= 0) return '00:00:00';
				
				const hours = Math.floor(this.countdownTime / 3600);
				const minutes = Math.floor((this.countdownTime % 3600) / 60);
				const seconds = this.countdownTime % 60;
				
				return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
			}
		},
		onLoad(options) {
			// 接收从订单页面传递的订单信息
			if (options.orderInfo) {
				try {
					this.orderInfo = JSON.parse(decodeURIComponent(options.orderInfo));
					console.log('接收的订单信息:', this.orderInfo);
					
					// 初始化倒计时
					this.initCountdown();
				} catch (error) {
					console.error('解析订单信息失败:', error);
					uni.showToast({
						title: '订单信息错误',
						icon: 'none'
					});
				}
			}
		},
		
		onUnload() {
			// 页面卸载时清除定时器
			if (this.countdownTimer) {
				clearInterval(this.countdownTimer);
			}
			if (this.checkOrderStatusTimer) {
				clearInterval(this.checkOrderStatusTimer);
			}
		},

		methods: {
			// 初始化倒计时
			initCountdown() {
				// 获取订单创建时间，如果没有则使用当前时间
				const createTime = this.orderInfo.createTime ? new Date(this.orderInfo.createTime) : new Date();
				const now = new Date();
				
				// 计算剩余时间（秒）
				const timeoutSeconds = this.timeoutHours * 3600; // 超时时间转换为秒
				const elapsedSeconds = Math.floor((now - createTime) / 1000); // 已过去的时间
				this.countdownTime = Math.max(0, timeoutSeconds - elapsedSeconds);
				
				console.log('订单创建时间:', createTime);
				console.log('当前时间:', now);
				console.log('剩余时间(秒):', this.countdownTime);
				
				// 如果已经超时，直接处理
				if (this.countdownTime <= 0) {
					this.handleOrderTimeout();
					return;
				}
				
				// 启动倒计时
				this.startCountdown();
			},
			
			// 启动倒计时
			startCountdown() {
				this.countdownTimer = setInterval(() => {
					this.countdownTime--;
					
					if (this.countdownTime <= 0) {
						this.handleOrderTimeout();
					}
				}, 1000);
				
				// 每30秒检查一次订单是否已被后端取消
				this.checkOrderStatusTimer = setInterval(() => {
					this.checkOrderStatus();
				}, 30000);
			},
			
			// 处理订单超时
			handleOrderTimeout() {
				// 清除定时器
				if (this.countdownTimer) {
					clearInterval(this.countdownTimer);
					this.countdownTimer = null;
				}
				if (this.checkOrderStatusTimer) {
					clearInterval(this.checkOrderStatusTimer);
					this.checkOrderStatusTimer = null;
				}
				
				// 显示超时提示
				uni.showModal({
					title: '订单超时',
					content: '订单已超时，将自动取消',
					showCancel: false,
					success: () => {
						// 跳转回订单页面或首页
						uni.switchTab({
							url: '/pages/index/index'
						});
					}
				});
			},
			
			// 检查订单状态
			async checkOrderStatus() {
				if (!this.orderInfo.orderId) return;
				
				try {
					const res = await api.checkOrderTimeout(this.orderInfo.orderId);
					if (res.code === 200 && res.data === true) {
						// 订单已被后端取消
						this.handleOrderTimeout();
					}
				} catch (error) {
					console.error('检查订单状态失败:', error);
				}
			},
			
			//选择支付方式
			changePayType(type) {
				this.payType = type;
			},
			//确认支付
			confirm: async function() {
				if (!this.orderInfo.orderId) {
					uni.showToast({
						title: '订单信息缺失',
						icon: 'none'
					});
					return;
				}
				
				// 构建支付请求参数
				const payDto = {
					sysType: this.payType, // 1:微信, 2:支付宝, 3:钱包支付
					orderIds: this.orderInfo.orderId,
					payAmount: Math.round(this.orderInfo.payAmount * 100) // 转换为分
				};
				
				uni.showLoading({
					title: '支付中...'
				});
				
				try {
					const payRes = await api.paymentPay(payDto);
					uni.hideLoading();
					
					if (payRes.code === 200) {
						uni.showToast({
							title: '支付成功',
							icon: 'success'
						});
						// 支付成功后跳转到支付成功页
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/money/paySuccess'
							});
						}, 1500);
					} else {
						uni.showToast({
							title: payRes.msg || '支付失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: '支付异常',
						icon: 'none'
					});
					console.error('支付异常:', error);
				}
			},
		}
	}
</script>

<style lang='scss'>
	.app {
		width: 100%;
	}

	.price-box {
		background-color: #fff;
		height: 265upx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28upx;
		color: #909399;

		.price{
			font-size: 50upx;
			color: #303133;
			margin-top: 12upx;
			&:before{
				content: '￥';
				font-size: 40upx;
			}
		}
	}
	
	/* 倒计时样式 */
	.countdown-box {
		background-color: #fff;
		margin-top: 20upx;
		padding: 30upx;
		text-align: center;
		border-radius: 10upx;
		margin-left: 20upx;
		margin-right: 20upx;
		
		.countdown-title {
			font-size: 28upx;
			color: #666;
			margin-bottom: 20upx;
		}
		
		.countdown-time {
			font-size: 48upx;
			color: #ff6b6b;
			font-weight: bold;
			font-family: 'Courier New', monospace;
		}
	}
	
	/* 商品信息样式 */
	.goods-section {
		margin-top: 20upx;
		background: #fff;
		padding-bottom: 1px;

		.g-header {
			display: flex;
			align-items: center;
			height: 84upx;
			padding: 0 30upx;
			position: relative;
		}

		.logo {
			display: block;
			width: 50upx;
			height: 50upx;
			border-radius: 100px;
		}

		.name {
			font-size: 30upx;
			color: $font-color-base;
			margin-left: 24upx;
		}

		.g-item {
			display: flex;
			margin: 20upx 30upx;

			image {
				flex-shrink: 0;
				display: block;
				width: 140upx;
				height: 140upx;
				border-radius: 4upx;
			}

			.right {
				flex: 1;
				padding-left: 24upx;
				overflow: hidden;
			}

			.title {
				font-size: 30upx;
				color: $font-color-dark;
			}

			.spec {
				font-size: 26upx;
				color: $font-color-light;
			}

			.price-box {
				display: flex;
				align-items: center;
				font-size: 32upx;
				color: $font-color-dark;
				padding-top: 10upx;

				.price {
					margin-bottom: 4upx;
				}
				.number{
					font-size: 26upx;
					color: $font-color-base;
					margin-left: 20upx;
				}
			}
		}
	}

	.pay-type-list {
		margin-top: 20upx;
		background-color: #fff;
		padding-left: 60upx;
		
		.type-item{
			height: 120upx;
			padding: 20upx 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-right: 60upx;
			font-size: 30upx;
			position:relative;
		}
		
		.icon{
			width: 100upx;
			font-size: 52upx;
		}
		.icon-erjiye-yucunkuan {
			color: #fe8e2e;
		}
		.icon-weixinzhifu {
			color: #36cb59;
		}
		.icon-alipay {
			color: #01aaef;
		}
		.tit{
			font-size: $font-lg;
			color: $font-color-dark;
			margin-bottom: 4upx;
		}
		.con{
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-sm;
			color: $font-color-light;
		}
	}
	.mix-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 630upx;
		height: 80upx;
		margin: 80upx auto 30upx;
		font-size: $font-lg;
		color: #fff;
		background-color: $base-color;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	}

</style>
